package com.example.chatweb.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * <h3>chat-web</h3>
 *
 * @author HuangJiayu
 * @description <p>redis配置类</p>
 * @date 2024-04-05 17:55
 **/
@Configuration
public class RedisConfig {
	
	@Autowired
	private RedisConnectionFactory factory;
	
	//	由于SpringBoot给我的是<Object,Object>的泛型，而我们需要第一个是String的，所以我们需要重新配置一下
	@Bean
	@SuppressWarnings("all")
	public RedisTemplate<String, Object> redisTemplate() {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(factory);
		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(
		 Object.class);
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
		StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//        key 采用 String 的序列化方式
		template.setKeySerializer(stringRedisSerializer);
//        hash 的 key 也采用 String 的序列化方式
		template.setHashKeySerializer(stringRedisSerializer);
//        value 的序列化方式采用 JSON
		template.setValueSerializer(jackson2JsonRedisSerializer);
//        hash value 的序列化方式也采用 JSON
		template.setHashValueSerializer(jackson2JsonRedisSerializer);
		template.afterPropertiesSet();
		return template;
	}
}
